import { Component, OnInit } from '@angular/core';
import { AxiosService } from '../../axios.service';
import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';

@Component({
  selector: 'app-emp-zhijian',
  templateUrl: './emp-zhijian.component.html',
  styleUrls: ['./emp-zhijian.component.scss']
})
export class EmpZhijianComponent implements OnInit {

  public isShow = {};//是否显示Delay
  timeCheck;//送检时间
  timeDelay;//送检时间当天16：30(Delay时间)
  timeNow;//当前系统时间

  public tempData = [];

  public listOfData = [];//工单文件区数据

  showWarning = {};//工件行显示退回图标
  showBigWarning;////工单行显示退回图标

  unionKey;//工单key
  workKey;//工件key

  public workData = [];
  //意同workData
  public dataWork = []; //筛选
  searchValue = ''; //筛选框输入的内容
  // listOfDisplayData = [];

  timeDic = {};

  addTime;//添加时间弹框
  isOkLoadingTime;
  time;//添加时间值

  union_order;//工单号
  sheet_order;//工件号
  id;

  addRemark1;//编辑设计备注
  isOkLoadingRemark;
  designRemark;

  updateData;
  //接收搜索前的数据；
  bodylistdata;
  sfmtime = new Array;
  cdcd;
  listfd = [];
  sjsjbigkey;
  sjsjkey;
  sjsjcd;

  constructor(
    public axios: AxiosService,
    private storage: LocalStorageService,
    public activatedRoute: ActivatedRoute,
    private router: Router
  ) {
    this.activatedRoute.params.subscribe((data) => {
      if (data) {
        console.log("----------------------------\n", data)
        // this.nameTitle = data.name;
        // console.log(this.nameTitle)
      }
    })
  }

  ngOnInit(): void {
    //获取全部数据
    this.getAllData();
  }

  //获取全部数据
  getAllData() {
    this.axios.axiosPost('QueryUnionOrder', { "stage": 3, "stageValue": 1, box: this.searchValue })
      .then((data) => {
        if (data) {
          // debugger
          this.listfd = [];
          console.log(data)
          this.sfmtime.splice(0, this.sfmtime.length)
          this.tempData = data['order'];
          this.cdcd = this.tempData.length;
          for (let i = 0; i < this.tempData.length; i++) {
            var b = [];
            this.tempData[i].show = false;
            this.sfmtime.push(b);
            this.listfd.push(new Array)
          }
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  //是否显示Delay
  showDelay(date) {
    let showTime = new Date();
    let yy = showTime.getFullYear();
    let MM = showTime.getMonth() + 1;
    let dd = showTime.getDate();//获取当前日期数
    let HH = showTime.getHours();//获取当前小时数(0-23)
    let mm = showTime.getMinutes();//获取当前分钟数(0-59)
    let timestamp = yy + '/' + MM + '/' + dd + ' ' + HH + ':' + mm;//当前系统时间
    let day;
    let delay;
    if (date === '0') {
      delay = '0000/00/00 00:00';
    } else {
      day = date.split('/')[2];
      delay = date.split('/')[0] + '/' + date.split('/')[1] + '/' + day.split(' ')[0] + ' ' + 16 + ':' + 30;//送检时间当天16：30
    }
    // console.log(delay)
    //时间戳转换

    this.timeCheck = new Date(date).getTime();//送检时间
    this.timeDelay = new Date(delay).getTime();//送检时间当天16：30(Delay时间)
    this.timeNow = new Date(timestamp).getTime();//当前系统时间
  }

  //查询工单对应的工件信息
  QueryWorkOrder(key) {
    console.log("key", key);
    if (this.tempData[key].show == true) {
      this.tempData[key].show = false;
    } else {
      this.tempData[key].show = true;
    }
    this.unionKey = key;
    this.workKey = key;
    console.log(this.searchValue)
    console.log(this.tempData[key].union_order)
    this.axios.axiosPost('QueryWorkOrder', { 'unionorder': this.tempData[key].union_order, "status": 3, "box": this.searchValue })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok' && data['order'].length >= 0) {
          // debugger
          const orderData = data['order'];
          //过滤标准件，只显示加工件
          let a = orderData.filter((item, i) => { return item.type_flag !== 0; })
          this.workData[key] = a;
          this.dataWork = a;
          // console.log(this.workData)
          const tempArr = [];
          const timeDefault = [];
          const dateList = [];//送检时间 数组
          const statusList = [];
          this.sfmtime[key] = [];
          this.listfd[key] = new Array
          for (var t = 0; t < this.workData[key].length; t++) {
            this.listfd[key].push(new Array)
            var sss = {
              zs: false, sj: "00:00:00", mp: false, jsq: "", ks: "", kg: false
            }
            this.sfmtime[key].push(sss)
          }
          for (let i = 0; i < a.length; i++) {
            if (a[i]['remark'] !== '') {
              tempArr.push(true);
            } else {
              tempArr.push(false);
            }
            //获取到工件的送检时间数组
            if (a[i]['check_date'] !== '') {
              dateList.push(a[i]['check_date']);
            } else {
              dateList.push('0');
            }
            //获取到工件的品检状态
            statusList.push(a[i]['check_status']);
            // 给点击的小行数据初始化时间
            timeDefault.push('');
          }
          // console.log('----------\n', dateList, statusList);
          //遍历日期
          // debugger
          const isShowList = [];
          for (let i = 0; i < a.length; i++) {
            let date = dateList[i];
            let status = statusList[i];
            this.showDelay(date);
            // console.log("送检时间", this.timeCheck)
            // console.log("送检时间当天16：30", this.timeDelay)
            // console.log("当前时间", this.timeNow)
            // console.log(status)
            if (status === '0') {
              // 四点半之前送来的  
              if (this.timeDelay >= this.timeCheck) {
                // 比较实际时间 和送检当天4点半
                if (this.timeNow >= this.timeDelay) {
                  console.log("爆炸")
                  isShowList.push(true);
                } else {
                  isShowList.push(false);
                }
              } else {
                // 四点半之后送来的
                var si = this.timeNow - 86400000
                console.log(si)
                if (si >= this.timeDelay) {
                  isShowList.push(true);
                } else {
                  isShowList.push(false);
                }
              }
            } else {
              isShowList.push(false)
            }
            //添加送检时间后，在当天16：30之后送检状态还是‘品检中’，且至以后都未发生变化，则显示Delay
            // if(status === '0' && this.timeCheck < this.timeDelay && this.timeNow > this.timeDelay){
            //   isShowList.push(true);
            // }
            //若添加送检时间超出当天16：30，显示Delay
            // else if(status === '0' && this.timeCheck > this.timeDelay){
            //   isShowList.push(true);
            // }
            // else{
            //   isShowList.push(false);
            // }
          }
          this.showWarning[key] = tempArr;
          this.isShow[key] = isShowList;
          this.timeDic[this.unionKey] = timeDefault;
          // console.log('1111111\n', this.showWarning, this.isShow)
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  //添加送检时间
  addDate(item, bigkey, key) {
    this.sjsjbigkey = bigkey;
    this.sjsjkey = key;
    this.sjsjcd = item;
    console.log(item)
    this.id = item.id;
    this.union_order = item.union_order;
    this.sheet_order = item.sheet_order;
    this.addTime = true;
    var showTime = new Date();
    let year = showTime.getFullYear();
    let mon = showTime.getMonth() + 1 < 10 ? "0" + (showTime.getMonth() + 1) : showTime.getMonth() + 1;;
    let da = showTime.getDate() < 10 ? "0" + showTime.getDate() : showTime.getDate();
    let hour = showTime.getHours() < 10 ? "0" + showTime.getHours() : showTime.getHours();
    let munite = showTime.getMinutes() < 10 ? "0" + showTime.getMinutes() : showTime.getMinutes();
    this.time = year + '/' + mon + '/' + da + ' ' + hour + ':' + munite;
  }

  //取消添加时间
  CancelAddTime() {
    this.addTime = false;
  }

  //确定添加时间
  addTimeOk() {
    console.log(this.sjsjbigkey);

    this.isOkLoadingTime = true;
    this.addTime = false;
    this.isOkLoadingTime = false;
    let check_status;
    if (!this.time) {
      check_status = '';
    } else {
      check_status = '0';
    }
    this.axios.axiosPost('UpdateWorkOrder', {
      'unionorder': this.union_order, 'workorder': this.sheet_order, id: this.id, 'check_date': this.time, 'check_status': check_status
    })
      .then((data) => {
        if (data['result'] === 'ok') {
          this.axios.axiosPost('UpdateCncData', { 'unionorder': this.union_order, 'workorder': this.sheet_order, id: this.id, 'songjian_shijian': this.time })
            .then((data) => {
              console.log(data)
              if (data['result'] === 'ok') {
                if (this.sjsjcd['chaidan'] == 1) {
                  this.QueryWorkOrder2(this.sjsjcd, this.sjsjbigkey, this.sjsjkey)
                } else {
                  this.QueryWorkOrder(this.sjsjbigkey)
                }
              }
            })

        }
      })
  }

  reset() {
    this.searchValue = '';
    this.getAllData();
  }

  //箱号筛选
  search() {
    this.getAllData();
  }

  //点击箱号跳转
  showBox(item) {
    console.log(item)
    const data = {};
    data['box'] = item.box;
    data['unionorder'] = item.union_order;
    data["ly"] = window.location.href;
    this.router.navigate(['/zhijianChild', data]);
    // console.log(item)
  }
  //点击设计备注
  addRemark(item) {
    this.addRemark1 = true;
    this.designRemark = item.check_remark;
    this.updateData = item;
  }
  //确认添加设计备注
  addRemarkOk() {
    this.isOkLoadingRemark = true;
    this.addRemark1 = false;
    this.isOkLoadingRemark = false;
    console.log("请求的参数", this.updateData.union_order, this.updateData.sheet_order)
    console.log("设置的字段", this.designRemark)
    this.axios.axiosPost('UpdateWorkOrder', {
      'unionorder': this.updateData.union_order, 'workorder': this.updateData.sheet_order,
      'check_remark': this.designRemark,
    })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
        }
      })
    this.QueryWorkOrder(this.unionKey);

  }

  //取消添加设计备注
  CancelAddRemark() {
    this.addRemark1 = false;
  }
  //点击行显示计时器
  clickLine(bigkey, key, item2) {
    if (this.sfmtime[bigkey][key].mp == false) {
      this.sfmtime[bigkey][key].zs = true;
      this.sfmtime[bigkey][key].mp == true;
      if (item2) {
        console.log(item2);
        // console.log("开始");
        this.sfmtime[bigkey][key].jsq = setInterval(() => {
          this.sfmtime[bigkey][key].sj = this.timeof(new Date().getTime() - item2)
        }, 1000)
      }
      console.log(item2);
    }
  }

  //开始计时
  start(bigkey, key, item2) {
    if (this.sfmtime[bigkey][key].kg == false) {
      this.sfmtime[bigkey][key].kg = true;
      if (this.sfmtime[bigkey][key].sj == "00:00:00") {
        this.axios.axiosPost('UpdateWorkOrder', {
          'unionorder': item2.union_order, 'workorder': item2.sheet_order,
          'timestamp': new Date().getTime()
        }).then((data) => {
          console.log(data);
          if (data["result"] == "ok") {
            this.workData[bigkey][key].timestamp = new Date().getTime();
            this.clickLine(bigkey, key, new Date().getTime());
          }
        })

      } else {
        alert("已經開始計時了")
      }
      // this.sfmtime[bigkey][key].ks = new Date().getTime();
      // this.sfmtime[bigkey][key].jsq = setInterval(() => {
      //   this.sfmtime[bigkey][key].sj = this.timeof(new Date().getTime() - this.sfmtime[bigkey][key].ks)
      //   console.log("aaaa")s
      // }, 1000)
    } else {
      alert("已經開始計時，請勿重復操作")
    }
  }



  //结束计时
  end(item, bigkey, key) {
    if (item.timestamp || this.sfmtime[bigkey][key].sj != "00:00:00") {
      clearInterval(this.sfmtime[bigkey][key].jsq)
      this.axios.axiosPost('AddWorkTime', { 'unionorder': item.union_order, "id": item.id, 'endtime': new Date().getTime(), "stage": 3 })
        .then((data) => {
          console.log(data)
          if (data['result'] === 'ok') {
            console.log("真棒");
            clearInterval(this.sfmtime[bigkey][key].jsq)
            this.sfmtime[bigkey][key].sj = "00:00:00";
            this.sfmtime[bigkey][key].mp = false;
            this.sfmtime[bigkey][key].kg = false;
            this.sfmtime[bigkey][key].zs = false;
            this.sfmtime[bigkey][key].ks = "";
            this.workData[bigkey][key].timestamp = "";
            console.log(this.workData[bigkey][key].timestamp);

            // this.QueryWorkOrder(bigkey)
          }
        })
    } else {
      alert("此工件未開始計時")
    }



  }
  timeof(data) {
    var s;
    var hours: number;
    // hours=parseInt((1000 % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    hours = parseInt((data % (1000 * 60 * 60 * 24) / (1000 * 60 * 60)).toString())
    // parseInt((1000 % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    console.log(hours)
    var minutes = parseInt(((data % (1000 * 60 * 60)) / (1000 * 60)).toString());
    var seconds = parseInt(((data % (1000 * 60)) / 1000).toString());
    s = (hours < 10 ? ('0' + hours) : hours) + ':' + (minutes < 10 ? ('0' + minutes) : minutes) + ':' + (seconds < 10 ? ('0' + seconds) : seconds);
    console.log(s)
    return s;
  }

  //结束页面生命周期
  ngOnDestroy(): void {

  }
  QueryWorkOrder2(a, b, c) {
    console.log("触发", a)
    this.axios.axiosPost("QueryCncDataSubOrder", { "unionorder": a.unionorder, "workorder": a.workorder, status: 3 }).then((data) => {
      console.log(data);
      if (data["result"] == "ok") {
        this.listfd[b][c] = data["order"];
      }
    })
  }

}
